// pages/index/index.js
var netWork = require('../../../../utils/netWork.js');
var api = require('../../../../utils/api.js');
var apiCode = require('../../../../utils/openApiCode.js');
const log = require('../../../../utils/logs.js');
const QR = require('../../../../utils/weapp-qrcode.js')
var Base64 = require('../../../../utils/base64.js');
import {playAudio,authUserPhone} from "../../../../utils/publicMethods";
const app = getApp();
let latitude = ''; //纬度
let longitude = ''; //纬度
let accuracy = ''; //位置精度
let speed = ''; //速度
let positioningType = '';
let positioningStyle = ''; 
var isClick = true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imagesUrl: getApp().globalData.imagesUrl,
    topHeight: 0,
    ani: 0, //动画是否执行
    prizeAni: 0,
    isSetting: 0,
    isShowModalAuth: false, //是否显示授权按钮
    isShowModalRule: false, //是否显示活动规则
    canIUseGetUserProfile: false,
    isXyr: false, //是否为心悠然产品
    isShowPrizes: false, //抽奖成功，显示领取成功页面
    isShowQRcode: false, //核销礼券页面
    addressShow: false,
    jfShow: false, //展示积分
    star1: 0,
    star2: 0,
    star3: 0,
    star4: 0,
    isFinsh: false,
    goToPage: 2, //1-中奖记录，2-关注公众号
    isQuestMask: false, //显示问卷调查
    prizeOrderId: "",
    questPage: 1, //问卷第1页
    isLoading: false,
    isQuest: false,
    questionAnswer: {
      "1": "",
      "2": "",
      "3": "",
      "4": "",
      "5": "",
      "6": "",
      "7": "",
      "8": ""
    },
    isSubMsg: false, //引导订阅
    isShowPub: false, //显示引导点击关注
    isChooseAvatar:false//判断当前版本是否支持最新的用户授权
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.isLoading(true, "正在加载中...");
  
    log.info("[index]--->[onLoad]")
    try {
      const {
        SDKVersion = ''
      } = wx.getSystemInfoSync();
      // 获取系统信息
      const that = this;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            addHeight: (res.screenHeight * res.pixelRatio - 1334) / 6
          });
        }
      });
      console.log(that.data.addHeight)
      log.info(SDKVersion)
      const compatibility = util.compareVersion(SDKVersion, '2.2.2');
      log.info(compatibility)
      if (compatibility == -1) {
        wx.showModal({
          content: '您的微信版本过低，请升级后再来吧~',
          confirmText: '我知道了',
          showCancel: false
        });
        return;
      }
    } catch (e) {}
    //高度处理
    let topHeight = wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight');
    console.log(wx.getStorageSync('isShowPrizes'))
    console.log(topHeight+'topHeight')
    this.setData({
      qrcode: wx.getStorageSync('qrCode'),
      topHeight: topHeight,
      goToganguo: wx.getStorageSync('goToganguo'),
      getUserinfo: wx.getStorageSync('getUserinfo'),
      getPhone: wx.getStorageSync('getPhone'),
      userType: wx.getStorageSync('userType'),
      prizeList: wx.getStorageSync('prizeList'),
      isShowPrizes: wx.getStorageSync('isShowPrizes') == '' || wx.getStorageSync('isShowPrizes') == null ? false : true,
      qrcodeBigURL: '',
      icon: wx.getStorageSync('productType') == 4||wx.getStorageSync('productType') == 5 ? 'xinyouranPage/loading_logo' : 'common/loading',
      isChooseAvatar:wx.canIUse('button.open-type.chooseAvatar')
    });

    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }

    // 获取jsCode
    this.updateJSCode();
    if (options.oper == 'close') {
      this.queryKingVIPMember();
      return;
    }
    if (options.source == 'readRule') {
      wx.setStorageSync('userType', 2) //老用户
      this.setData({
        source: options.source,
      })
      longitude = options.longitude;
      latitude = options.latitude
      //勾选银隐私页，授权抽奖
      this.draw();

    }
    //从消息通知进入到中奖记录页面后奖品已经过期或已领取返回首页提示
    let showToastText = wx.getStorageSync('showToastText')
    if(showToastText){
        this.setData({
            showToastText,
            showToast:true
        })
        setTimeout(() => {
            this.setData({
                showToast:false
            })
        }, 3000);
        wx.removeStorageSync('showToastText')
    }
  },
  onReady: function () {

  },
  /**
   *查询是否为金蝶会员
   *20230207 注释掉查询金蝶会员代码和问卷调查
   *由于问卷调查被主调所以添加积分接口也不会再调用
   */
  queryKingVIPMember: function () {
    const that = this;
    if (that.data.isShowPrizes == false) { //点击关闭，引导点击历史记录

      let query = wx.createSelectorQuery();
      query.select('.bnt-rm').boundingClientRect(rect => {
        let clientWidth = rect.width;
        let ratio = 750 / clientWidth;
        let clientTop = rect.top;
        let top = clientTop * ratio - 360;
        that.setData({
          pubtop: top,
          isShowMore: true
        })
        console.log('pubtop:'+top)
      }).exec();
    }
    // if (!this.data.isQuest) {
    //   // api.showLoading('正在加载中...')
    //   netWork.POST('xhtx/little/queryKingVIPMember', {
    //     data: {
    //       userId: wx.getStorageSync('userId'),
    //       prizeOrderId: that.data.prizeOrderId
    //     },
    //     success: function (res) {

    //       if (res.data.retCode == "0000") {
    //         if (res.data.data.cardNo != "") {
    //           that.setData({
    //             isQuestMask: true,
    //             isQuest: true,
    //             cardNo: res.data.data.cardNo
    //           });
    //           return;
    //         } else {
    //           if (that.data.isShowPrizes == false) { //点击关闭，引导点击历史记录
    //             setTimeout(function () {
    //               let query = wx.createSelectorQuery();
    //               query.select('.bnt-rm').boundingClientRect(rect => {
    //                 let clientWidth = rect.width;
    //                 let ratio = 750 / clientWidth;
    //                 let clientTop = rect.top;
    //                 let top = clientTop * ratio - 350;
    //                 that.setData({
    //                   pubtop: top,
    //                   isShowMore:true,
    //                   // isShowPub: true
    //                 })
    //               }).exec();
    //             }, 1000)


    //           }
    //         }
    //       } else {
    //         if (that.data.isShowPrizes == false) { //点击关闭，引导点击历史记录
    //           setTimeout(function () {
    //             let query = wx.createSelectorQuery();
    //             query.select('.bnt-rm').boundingClientRect(rect => {
    //               let clientWidth = rect.width;
    //               let ratio = 750 / clientWidth;
    //               let clientTop = rect.top;
    //               let top = clientTop * ratio - 350;
    //               that.setData({
    //                 pubtop: top,
    //                 isShowPub: true
    //               })
    //             }).exec();
    //           }, 1000)

    //         }
    //       }
    //     },
    //     fail: function () {
    //       if (that.data.isShowPrizes == false) { //点击关闭，引导点击历史记录
    //         setTimeout(function () {
    //           let query = wx.createSelectorQuery();
    //           query.select('.bnt-rm').boundingClientRect(rect => {
    //             let clientWidth = rect.width;
    //             let ratio = 750 / clientWidth;
    //             let clientTop = rect.top;
    //             let top = clientTop * ratio - 350;
    //             that.setData({
    //               pubtop: top,
    //               isShowPub: true
    //             })
    //           }).exec();
    //         }, 1000)

    //       }
    //     }
    //   });
    // } else {
    //   console.log('that.data.isShowPrizes' + that.data.isShowPrizes)
    //   if (that.data.isShowPrizes == false) { //点击关闭，引导点击历史记录
    //     setTimeout(function () {
    //       let query = wx.createSelectorQuery();
    //       query.select('.bnt-rm').boundingClientRect(rect => {
    //         let clientWidth = rect.width;
    //         let ratio = 750 / clientWidth;
    //         let clientTop = rect.top;
    //         let top = clientTop * ratio - 350;
    //         that.setData({
    //           pubtop: top,
    //           isShowPub: true
    //         })
    //       }).exec();
    //     }, 1000)

  },
  showjfGif() {
    const that = this;
    let query2 = wx.createSelectorQuery();
    query2.select('.succ-left-ani').boundingClientRect(rect2 => {
      that.setData({
        top: rect2.top + 45,
        left: rect2.left + 50
      })
      console.log('top' + that.data.top)

    }).exec();
    query2.select('.bottom-sview').boundingClientRect(rect2 => {
      that.setData({
        gifHeight: rect2.top - that.data.top
      })
      console.log('gifHeight' + that.data.gifHeight)
    }).exec();

    setTimeout(() => {
      that.jfGif();
    }, 1000);
  },
  onShow: function () {
    if (wx.getStorageSync('gzhPayAuthNew') == '' || wx.getStorageSync('gzhPayAuthNew') == null) {
        console.info("[存入session中的gzhPayAuthNew]" + wx.getStorageSync('gzhPayAuthNew'))
        wx.redirectTo({
            url: '../../../scan/scan'
        })
    }
    try {
        // 检测是否可以调用getUpdateManager检查更新
        if (!wx.canIUse("getUpdateManager")) return;
        let updateManager = wx.getUpdateManager();
        // 获取全局唯一的版本更新管理器，用于管理小程序更新
        updateManager.onCheckForUpdate(function (res) {
          log.info(res)
          // 监听向微信后台请求检查更新结果事件
          log.info("是否有新版本：" + res.hasUpdate);
          if (res.hasUpdate) {
            //如果有新版本
            // 小程序有新版本，会主动触发下载操作
            updateManager.onUpdateReady(function () {
              //当新版本下载完成，会进行回调
              wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，单击确定重启小程序',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启小程序
                    updateManager.applyUpdate();
                  }
                }
              })
            })
            // 小程序有新版本，会主动触发下载操作（无需开发者触发）
            updateManager.onUpdateFailed(function () {
              //当新版本下载失败，会进行回调
              wx.showModal({
                title: '提示',
                content: '检查到有新版本，但下载失败，请稍后尝试',
                showCancel: false,
              })
            })
          }
        });
      } catch (e) {
        e
      }
      try {
        if (wx.onNeedPrivacyAuthorization) {
            wx.onNeedPrivacyAuthorization(resolve => {
                this.selectComponent('#privacyPopup').show();//这里是让组件弹窗显示
                this.selectComponent('#privacyPopup').data.parentPageInfo = this;
                this.resolvePrivacyAuthorization = resolve
            })
        }
     } catch (error) {
        console.info(error)
     }
  },
  jfGif() {
    const that = this;
    var animation = wx.createAnimation({
      duration: 1500,
      timingFunction: 'ease-in',
      delay: 1000
    });
    animation.opacity(0.6).translate(170, that.data.gifHeight).step()
    var animation1 = wx.createAnimation({
      duration: 1500,
      timingFunction: 'ease-in',
      delay: 1100
    });
    animation1.opacity(0.6).translate(170, that.data.gifHeight).step()
    var animation2 = wx.createAnimation({
      duration: 1500,
      timingFunction: 'ease-in',
      delay: 1200
    });
    animation2.opacity(0.6).translate(170, that.data.gifHeight).step()
    var animation3 = wx.createAnimation({
      duration: 1500,
      timingFunction: 'ease-in',
      delay: 1300
    });
    animation3.opacity(0.6).translate(170, that.data.gifHeight).step()
    var animation4 = wx.createAnimation({
      duration: 1500,
      timingFunction: 'ease-in',
      delay: 1400
    });
    animation4.opacity(0.6).translate(170, that.data.gifHeight).step()
    var animation5 = wx.createAnimation({
      duration: 1500,
      timingFunction: 'ease-in',
      delay: 1500
    });
    animation5.opacity(0.6).translate(170, that.data.gifHeight).step()
    this.setData({
      ani: [animation.export(), animation1.export(), animation2.export(), animation3.export(), animation4.export(), animation5.export()]
    })
    setTimeout(() => {
      that.setData({
        jfShow: false
      })
    }, 2700);

  },
  //生成二维码
  drawImg: function (ticketNo) {
    var imgData = QR.drawImg(ticketNo, {
      typeNumber: 4,
      errorCorrectLevel: 'M',
      size: 500
    })
    return imgData;
  },

  updateJSCode() {
    api.cancelLoading();
    wx.login({
      success: res => {
        console.log("[onLoad--wx.login]" + res.code);
        if (res.code) {
          wx.setStorageSync('code', res.code)
        } else {
          console.log("获取jsCode失败" + res.errMsg);
        }
      }
    });
  },
  /**
   * 点击酒瓶或按钮，进行授权或抽奖操作
   */
  onclickBottle: async function () {
    log.info("[index]--->[点击进入]")
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })

    if (wx.getStorageSync('qrCode') == null || wx.getStorageSync('qrCode') == undefined || wx.getStorageSync('qrCode') == '') { //无码用户进入小程序,新用户
      // 无码进入，调用摄像头进行扫码
      api.scanCode();
    } else {
      if (wx.getStorageSync('userType') == '1') {
        wx.redirectTo({
          url: '../readRule/readRule',
        })
        return;
      }
      //扫码抽奖
      this.scanQrcodeApi();
    }
  },
  scanCode() {
    wx.removeStorageSync('qrCode')
    // 无码进入，调用摄像头进行扫码
    api.scanCode();
  },
  /**
   * 调用扫码接口
   */
  scanQrcodeApi: function () {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    //防止重复点击或者点击过快
    console.log("点击了");
    if (!isClick) {
      console.log("重复返回~");
      return;
    }
    if (isClick) {
      isClick = false;
      //定时器
      setTimeout(function () {
        isClick = true;
      }, 2000); //3秒内不能重复点击
    }

    this.isLoading(true, "正在获取位置...");

    const that = this;
    wx.getLocation({
      type: 'wgs84',
      success: res => {
        that.isLoading(false)
        //存入地址
        latitude = res.latitude;
        longitude = res.longitude;
        speed = res.speed;
        accuracy = res.accuracy;
        wx.setStorageSync('latitude', latitude);
        wx.setStorageSync('longitude', longitude);
        wx.setStorageSync('speed', speed);
        wx.setStorageSync('accuracy', accuracy);
        console.info('抽奖接口');
        log.info('[index]--->[扫码接口]')
        that.draw();
      },
      fail: res => {
        that.isLoading(false)
        log.error('[wx.getLocation===res.errMsg]' + JSON.stringify(res.errMsg))
        if (res.errMsg) {
          that.setData({
            isShowModalAuth: true,
            authText: "为了保证正常获取奖励，现需获取您的地理位置",
            isSetting: 1
          })
          return;
        }
      }
    })
  },

  draw: function () {
    this.isLoading(true, "正在抽奖...")
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    //2022.12.01新增需求抽奖播放音频
    //根据分支和地区播放不同的音频文件
    playAudio();
    const that = this;
    netWork.POST('lotteryNew/lottery', {
      data: {
        qrcodeAPublish: wx.getStorageSync('qrCode'),
        userId: wx.getStorageSync('userId'),
        latitude: latitude,
        longitude: longitude,
      },
      success: function (res) {
        that.isLoading(false)
        if (res.data.retCode == undefined) {
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          })
        }
        if (res.data.retCode == '0000') {
          //抽奖成功，跳转恭喜页面
          if (res.data.data != "" && res.data.data != null) {
            var qrcode = wx.getStorageSync('qrCode');
            wx.removeStorageSync('qrCode');
 

            //根据结果，判断中奖类型，进行跳转
            let plist = res.data.data.orderList;
            if (plist == null || plist == '' || plist == 'undefined') {
              //跳转温馨提示页面
              wx.redirectTo({
                url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
              })
            }

            that.setData({
              prizeList: plist,
              isShowPrizes: true, //领取成功页
            })
            //是否展示问卷
            var prizeOrderId = plist[0].prizeOrderId;
            if (prizeOrderId != "" || prizeOrderId != null) {
              that.setData({
                prizeOrderId: prizeOrderId
              })
            }
            try {
                if(JSON.stringify(res.data.data.subjoin) != '{}'){
                    if(res.data.data.subjoin.addSubjoin){
                        getApp().globalData.benefitCardSpeedData = res.data.data.subjoin.addSubjoin;
                    }else{
                        getApp().globalData.benefitCardSpeedData = "";
                    }
                    let useSubjoin = res.data.data.subjoin.useSubjoin;
                    if(useSubjoin){
                        for(let i of plist){
                            if(i.prizeOrderId == useSubjoin.doubleOrder){
                                i.doublePrizeAmount = useSubjoin.doublePrizeAmount;
                                i.doubleCount = useSubjoin.doubleCount;
                                i.prizeAmount = i.prizeAmount/useSubjoin.doubleCount;
                            }
                        }
                        getApp().globalData.doubleMoney = useSubjoin;
                    }else{
                        getApp().globalData.doubleMoney = {};
                    }
                }else{
                    getApp().globalData.doubleMoney = {};
                    getApp().globalData.benefitCardSpeedData = "";
                }
            } catch (error) {
                console.log('subjoin error')
            }
            wx.setStorageSync('prizeList', plist)
            wx.setStorageSync('isShowPrizes', true)
            if(wx.getStorageSync('isMemberDay')){
                wx.redirectTo({
                    url: '../memberDayPrize/memberDayPrize',
                  })
            }else{
                wx.redirectTo({
                    url: '../prize/prize',
                })
            }
            
          } else {
            let nickName = "";
            let luckyTime = "";
            if (res.data.data.nickName && res.data.data.nickName != null & res.data.data.nickName != "" && res.data.data.nickName != undefined) {
              nickName = res.data.data.nickName;
            }
            if (res.data.data.luckyTime && res.data.data.luckyTime != null & res.data.data.luckyTime != "" && res.data.data.luckyTime != undefined) {
              luckyTime = res.data.data.luckyTime;
            }
            //跳转温馨提示页面
            wx.redirectTo({
              url: '../prompt/prompt?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg + '&nickName=' + nickName + '&luckyTime=' + luckyTime,
            })
          }

        } else {
          if (typeof res.data.data != 'undefined' && typeof res.data.data.isXyr != 'undefined' && res.data.data.isXyr) {
            wx.redirectTo({
              url: '../xinyouran/xinyouran',
            })
            return;
          }
          let nickName = "";
          let luckyTime = "";
          if (typeof res.data.data != 'undefined' && res.data.data.nickName && res.data.data.nickName != null & res.data.data.nickName != "" && res.data.data.nickName != undefined) {
            nickName = res.data.data.nickName;
          }
          if (typeof res.data.data != 'undefined' && res.data.data.luckyTime && res.data.data.luckyTime != null & res.data.data.luckyTime != "" && res.data.data.luckyTime != undefined) {
            luckyTime = res.data.data.luckyTime;
          }
          //跳转温馨提示页面
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg + '&nickName=' + nickName + '&luckyTime=' + luckyTime,
          })
        }
      },
      fail: function (res) {
        that.isLoading(false)
        //跳转温馨提示页面
        wx.redirectTo({
          url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
        })
      }
    });
  },

  /**
   * 用户同意获取用户信息回调
   * @param {*} e 
   */
  async bindGetUserInfo(e) {
    console.log("old头像授权")

    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })

    this.setData({
      isLoading: true,
      loadingText: "正在获取信息..."
    })
    // api.showLoading('正在获取信息...')
    const that = this;
    if (e.detail.userInfo) {
      console.log('e.detail.userInfo' + JSON.stringify(e.detail.userInfo));
      //用户按了允许授权按钮
      app.globalData.userInfo = e.detail.userInfo;
      wx.setStorageSync('nickName', e.detail.userInfo.nickName);
      //遮罩层消失
      this.setData({
        isShowModalAuth: 0
      })
      //更新用户信息
      let res = await that.updateUserInfo(e.detail.encryptedData, e.detail.iv);
      that.updateJSCode();
      that.isLoading(false);
      if (!res) {
        wx.redirectTo({
          url: '../prompt/prompt?retCode=' + apiCode.AUTHFAIL.code + '&retMsg=' + apiCode.AUTHFAIL.msg,
        })
        return;
      }
      //已成功授权用户信息，并保存
      wx.setStorageSync('getUserinfo', true);
      console.log("开始授权手机号")
      that.setData({ //显示拒绝授权提示层
        isShowModalAuth: true,
        authText: "为了保证正常获取奖励，现需获取您的手机号码",
        isPhone: '1',
      })
    } else {
      that.isLoading(false);
      //用户按了拒绝按钮,显示授权遮罩层
      this.setData({
        isShowModalAuth: 1,
        authText: "为了保证正常获取奖励，现需获取您的头像昵称"
      })
      this.setData({
        isLoading: false,
      })
      return;
    }


  },
  /**
   * 用户同意获取用户信息回调
   * @param {*} e 
   */
  async bindGetUserInfo1(e) {
    console.log("old头像授权")

    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })

    this.setData({
      isLoading: true,
      loadingText: "正在获取信息..."
    })
    // api.showLoading('正在获取信息...')
    const that = this;
    if (e.detail.userInfo) {
      console.log('e.detail.userInfo' + JSON.stringify(e.detail.userInfo));
      //用户按了允许授权按钮
      app.globalData.userInfo = e.detail.userInfo;
      wx.setStorageSync('nickName', e.detail.userInfo.nickName);
      //遮罩层消失
      this.setData({
        isShowModalAuth: 0
      })
      //更新用户信息
      let res = await that.updateUserInfo(e.detail.encryptedData, e.detail.iv);
      that.updateJSCode();
      that.isLoading(false);
      if (!res) {
        wx.redirectTo({
          url: '../prompt/prompt?retCode=' + apiCode.AUTHFAIL.code + '&retMsg=' + apiCode.AUTHFAIL.msg,
        })
        return;
      }
      //已成功授权用户信息，并保存
      wx.setStorageSync('getUserinfo', true);
      that.showPrizeRecord();
    } else {
      that.isLoading(false);

      this.setData({
        isLoading: false,
      })
      wx.showToast({
        title: '取消授权',
        icon: 'none'
      })
      return;
    }


  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    console.log("new头像授权")

    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    this.isLoading(true, "正在获取信息...");
    const that = this;
    new Promise(function (resolve, reject) {
      wx.getUserProfile({
        desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          app.globalData.userInfo = res.userInfo;
          wx.setStorageSync('nickName', res.userInfo.nickName);
          wx.setStorageSync('getUserinfo', true);
          //遮罩层消失
          that.setData({
            isShowModalAuth: 0,
            getUserinfo: true,
          })
          resolve(res);
        },
        fail: (res) => {
          console.log("getUserProfile" + res)
          //用户按了拒绝按钮,显示授权遮罩层
          that.setData({
            isShowModalAuth: 1,
            authText: "为了保证正常获取奖励，现需获取您的头像昵称"
          })
          api.cancelLoading();

          resolve();
        }

      })
    }).then(
      async function (obj) {
        //更新用户信息
        let res = await that.updateUserInfo(obj.encryptedData, obj.iv);
        that.updateJSCode();
        that.isLoading(false)
        if (!res) {
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + apiCode.AUTHFAIL.code + '&retMsg=' + apiCode.AUTHFAIL.msg,
          })
          return;
        }
        //已成功授权用户信息，并保存
        wx.setStorageSync('getUserinfo', true);
        console.log("开始授权手机号")
        that.setData({ //显示拒绝授权提示层
          isShowModalAuth: true,
          authText: "为了保证正常获取奖励，现需获取您的手机号码",
          isPhone: '1',
        })
      }

    ).catch(() => {
      that.isLoading(false)
      console.log("信息授权失败啦")
    })




  },


  //中奖记录查询用
  getUserProfile1(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    console.log("new头像授权")

    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    this.isLoading(true, "正在获取信息...");
    const that = this;
    new Promise(function (resolve, reject) {
      wx.getUserProfile({
        desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          app.globalData.userInfo = res.userInfo;
          wx.setStorageSync('nickName', res.userInfo.nickName);
          wx.setStorageSync('getUserinfo', true);
          //遮罩层消失
          that.setData({
            isShowModalAuth: 0,
            getUserinfo: true,
          })
          resolve(res);
        },
        fail: (res) => {
          console.log("getUserProfile" + res)
          //用户按了拒绝按钮,显示授权遮罩层
          wx.showToast({
            title: '取消授权',
            icon: 'none'
          })
          resolve();
        }

      })
    }).then(
      async function (obj) {
        //更新用户信息
        let res = await that.updateUserInfo(obj.encryptedData, obj.iv);
        that.updateJSCode();
        that.isLoading(false)
        if (!res) {
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + apiCode.AUTHFAIL.code + '&retMsg=' + apiCode.AUTHFAIL.msg,
          })
          return;
        }
        //已成功授权用户信息，并保存
        wx.setStorageSync('getUserinfo', true);
        //查询中奖记录
        that.showPrizeRecord();
      }

    ).catch((e) => {
      that.isLoading(false)
      console.log("信息授权失败啦" + e)
    })




  },

  /**
   * 获取手机号
   * @param {*} e 
   */
  async getPhoneNumber(e) {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    if(e.detail.errno===1400001){
        wx.redirectTo({
            url: '../prompt/prompt?retCode=' + apiCode.PHONENUMERROR.code + '&retMsg=' + apiCode.PHONENUMERROR.msg,
        })
        return;
    }
    this.isLoading(true, "正在获取信息...")
    var that = this;
    if (e.detail.encryptedData != undefined) {
      that.setData({ //同意
        isShowModalAuth: false,
        getPhone: true
      })

      let res = await authUserPhone(e);
      this.updateJSCode();
      that.isLoading(false)
      if (!res) {
        wx.redirectTo({
          url: '../prompt/prompt?retCode=' + apiCode.AUTHFAIL.code + '&retMsg=' + apiCode.AUTHFAIL.msg,
        })
        return;
      }
      //已成功授权手机号，并保存
      wx.setStorageSync('getPhone', true);
      wx.setStorageSync('getUserinfo', true);
      this.scanQrcodeApi();
    } else {
      that.isLoading(false)
      that.setData({ //显示拒绝授权提示层
        isShowModalAuth: true,
        authText: "为了保证正常获取奖励，现需获取您的手机号码",
        isPhone: '1'
      })

    }
  },

  /**
   * 更新用户信息
   * @param {*} encryptedData 
   * @param {*} iv 
   */
  updateUserInfo(encryptedData, iv) {
    const that = this;
    console.log('updateUserInfo')
    return new Promise((resolve, reject) => {
      netWork.POST('updateUserInfo', {
        data: {
          userId: wx.getStorageSync('userId'),
          encryptedData: encodeURIComponent(encryptedData),
          iv: encodeURIComponent(iv),
          jsCode: wx.getStorageSync('code')
        },
        success: function (res) {
          if (res.data.retCode == undefined) {
            resolve(false);
          }
          if (res.data.retCode == '0000') {
            wx.setStorageSync('userPhone', res.data.data.phone);
            resolve(true);
          } else {
            resolve(false);
          }
        },
        fail: function (res) {
          resolve(false);
        }
      });
    });

  },

  /**
   * 显示活动规则
   */
  showRule: function () {
    // this.setData({
    //   isShowModalRule: true,
    //   ani: 0
    // })
    wx.navigateTo({
      url: '../ruleh5/ruleh5'
    })
  },

  /**
   * 关闭活动规则
   */
  clickClose: function () {
    this.setData({
      ani: 1
    })
    const that = this;
    setTimeout(function () {
      that.setData({
        isShowModalRule: false
      })
    }, 180);
  },

  /**
   * 更多活动， 跳转第三方小程序
   */
  showMore: function () {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })

    // this.queryIsFollowGG();
    wx.navigateTo({
      url: '../officialAccount/officialAccount',
    })
  },

  /**
   * 打开设置
   */
  openSetting() {
    this.setData({
      isShowModalAuth: false
    })
    api.putOpenSetting();
  },
  /**
   *查询是否关注公众号
   */
  queryIsFollow: function () {
    this.isLoading(true, "正在查询...");
    wx.redirectTo({
      url: '../../../prizeRecord/prizeRecord',
    })
    // const that = this;
    // netWork.POST('searchUserInfo', {
    //   data: {
    //     userId: wx.getStorageSync('userId')
    //   },
    //   success: function (res) {
    //     that.isLoading(false)
    //     that.setData({
    //       isShowPub: false
    //     })
    //     if (res.data.retCode == undefined) {
    //       wx.redirectTo({
    //         url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
    //       })
    //     }
    //     if (res.data.retCode == "0000") {
    //       if (res.data.data.isFollow == 1) { //关注
    //         //跳转中奖记录
    //         wx.redirectTo({
    //           url: '../prizeRecord/prizeRecord',
    //         })
    //       } else { //未关注，引导关注
    //         wx.navigateTo({
    //           url: '../officialAccount/officialAccount',
    //         })
    //       }

    //     } else { //失败，暂时不按未关注处理
    //       //跳转中奖记录
    //       wx.redirectTo({
    //         url: '../prizeRecord/prizeRecord',
    //       })
    //     }
    //   },
    //   fail: function () {
    //     that.setData({
    //       isShowPub: false
    //     })
    //     that.isLoading(false)
    //     //跳转中奖记录
    //     wx.redirectTo({
    //       url: '../prizeRecord/prizeRecord',
    //     })
    //   }
    // });
  },
  /**
   *查询是否关注公众号
   */
  queryIsFollowGG: function () {
    this.isLoading(true, "正在查询...");
    const that = this;
    netWork.POST('searchUserInfo', {
      data: {
        userId: wx.getStorageSync('userId')
      },
      success: function (res) {
        that.isLoading(false)
        that.setData({
          isShowPub: false
        })
        if (res.data.retCode == undefined) {
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          })
        }
        if (res.data.retCode == "0000") {
          if (res.data.data.isFollow == 1) { //关注
            //跳转中奖记录
            wx.navigateToMiniProgram({
              appId: api.thirdAppId,
              envVersion: getApp().globalData.ganguoAppidStyle
            })
          } else { //未关注，引导关注
            wx.navigateTo({
              url: '../officialAccount/officialAccount',
            })
          }

        } else { //失败，暂时不按未关注处理
          //跳转中奖记录
          wx.navigateToMiniProgram({
            appId: api.thirdAppId,
            path: 'pages/home/home',
            envVersion: getApp().globalData.ganguoAppidStyle
          })
        }
      },
      fail: function () {
        that.setData({
          isShowPub: false
        })
        that.isLoading(false)
        //跳转中奖记录
        wx.navigateToMiniProgram({
          appId: api.thirdAppId,
          path: 'pages/home/home',
          envVersion: getApp().globalData.ganguoAppidStyle
        })
      }
    });
  },
  /**
   * 跳转中奖记录页面
   */
  showPrizeRecord: function () {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    wx.removeStorageSync('isShowPrizes');
    wx.removeStorageSync('prizeList');
    this.queryIsFollow();
  },

  imageLoad: function () {
    this.setData({
      prizeAni: 1
    })
  },
  /**
   * 未中奖
   */
  notWinning: function (url, prizeOrderId, prizeId) {
    netWork.POST('xhtx/little/notWinning', {
      data: {
        userId: wx.getStorageSync('userId'),
        prizeOrderId: prizeOrderId,
        prizeId: prizeId,
        positioningStyle: positioningStyle,
        positioningType: positioningType,
        latitude: latitude,
        longitude: longitude,
        speed: speed,
        accuracy: accuracy
      },
      success: function (res) {
        if (res.data.retCode == undefined) {
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          })
        }
        if (res.data.retCode == '0000') {
          if (url != "" || url != null) {
            wx.redirectTo({
              url: url,
            })
          }

        } else if (res.data.retCode != '0000') {
          //跳转温馨提示页面
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
          })
        } else {
          //跳转温馨提示页面
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          })
        }
      },
      fail: function (res) {
        //跳转温馨提示页面
        wx.redirectTo({
          url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
        })
      }
    });
  },
  showBox() {

  },
  //将base64图片转网络图片
  sendCode(code) {
    let qrcode = code.replace(/\. +/g, '').replace(/[\r\n]/g, '')
    /*code是指图片base64格式数据*/
    //声明文件系统
    const fs = wx.getFileSystemManager();
    //随机定义路径名称
    var times = new Date().getTime();
    var codeImg = wx.env.USER_DATA_PATH + '/' + times + '.png';
    return new Promise((resolve, reject) => {
      //将base64图片写入
      fs.writeFile({
        filePath: codeImg,
        data: qrcode.slice(22),
        encoding: 'base64',
        success: () => {
          resolve(codeImg)
        }
      });
    })

  },
  async createCanvvasImage() {
    wx.showLoading({
      title: '正在保存...',
    })
    const that = this;
    let ticketNo = "【券号】" + this.data.ticket.FTicketNo; //累计金额
    let time = "【有效期】" + this.data.ticket.FBeginDate + "至" + this.data.ticket.FEndDate; //称号
    let rule1 = "1." + this.data.ticket.FConsumeRule;
    let rule2 = "2." + this.data.ticket.FUseRule
    //背景图
    let headImg = new Promise(function (resolve) {
      wx.getImageInfo({
        src: that.data.imagesUrl + '/successNew/qr_bg_cj.png',
        success: function (res) {
          resolve(res.path)
        },
        fail: function (err) {
          console.log(err)
          wx.showToast({
            title: '网络错误请稍后重试',
            icon: 'loading'
          })
        }
      })
    });
    //标题
    let titleImgLeft = new Promise(function (resolve) {
      wx.getImageInfo({
        src: that.data.imagesUrl + '/qrcode/ticket_title_l.png',
        success: function (res) {
          resolve(res.path)
        },
        fail: function (err) {
          console.log(err)
          wx.showToast({
            title: '网络错误请稍后重试',
            icon: 'loading'
          })
        }
      })
    });
    let titleImgRight = new Promise(function (resolve) {
      wx.getImageInfo({
        src: that.data.imagesUrl + '/qrcode/ticket_title_r.png',
        success: function (res) {
          resolve(res.path)
        },
        fail: function (err) {
          console.log(err)
          wx.showToast({
            title: '网络错误请稍后重试',
            icon: 'loading'
          })
        }
      })
    });
    let kfImg = new Promise(function (resolve) {
      wx.getImageInfo({
        src: that.data.imagesUrl + '/qrcode/kf.png',
        success: function (res) {
          resolve(res.path)
        },
        fail: function (err) {
          console.log(err)
          wx.showToast({
            title: '网络错误请稍后重试',
            icon: 'loading'
          })
        }
      })
    });
    let qrcodeUrl = await that.sendCode(that.data.qrcodeBigURL);
    //qrcode
    let qrcode = new Promise(function (resolve) {
      wx.getImageInfo({
        src: qrcodeUrl,
        success: function (res) {
          resolve(res.path)
        },
        fail: function (err) {
          console.log(err)
          wx.showToast({
            title: '网络错误请稍后重试',
            icon: 'loading'
          })
        }
      })
    });

    Promise.all([headImg, qrcode, titleImgLeft, titleImgRight, kfImg]).then(function (result) {
      const ctx = wx.createCanvasContext('myCanvas');
      let height = 0; //当前高度
      //背景图
      ctx.drawImage(result[0], 20, 50, 580, 880);
      //临时保存
      ctx.restore();
      //  //二维码
      // ctx.drawImage(result[2], 153, 90, 25, 19);
      ctx.font = 'normal bold 33px Source Han Sans CN';
      ctx.setFillStyle("#B72733"); // 文字颜色
      ctx.setTextAlign("center"); //居中
      ctx.fillText(that.data.ticketName, 310, 120); // 绘制文字
      //二维码
      if (that.data.ticket.FSource == '001') {
        ctx.drawImage(result[1], 190, 160, 250, 250);
      } else {
        ctx.drawImage(result[4], 190, 160, 250, 250);
      }
      //临时保存
      ctx.restore();
      ctx.font = 'normal bold 18px Source Han Sans CN';
      ctx.setFillStyle("#231815"); // 文字颜色
      ctx.setTextAlign("center"); //居中
      ctx.fillText(ticketNo, 300, 470); // 绘制文字
      //临时保存
      ctx.restore();
      ctx.fillText(time, 300, 510); // 绘制文字
      //临时保存
      ctx.restore();

      ctx.font = 'normal bold 18px Source Han Sans CN';
      ctx.setFillStyle("#231815"); // 文字颜色
      ctx.setTextAlign("left");
      ctx.fillText("使用规则:", 90, 570); // 绘制文字
      // //临时保存
      ctx.restore();

      var text = that.data.ticket.FNote;
      // console.log(text)
      var temp = text.split(/[\n,]/g);
      var heights = 610;
      // for(var i =0;i<temp.length;i++){

      // var he = that.drawText(ctx,temp[0],100, heights, heights,432) // 自动
      //heights =he+heights;
      // console.log(temp[i]);
      ctx.restore();
      that.drawText(ctx, temp, 90, heights, heights, 440); // 自动

      ctx.restore();

      // }
      // console.log(he+"he")
      //ctx.draw()
      // ctx.fillText(rule1, 100, 630); // 绘制文字
      //  //临时保存
      //  ctx.restore();
      // ctx.fillText(rule2, 100, 660); // 绘制文字 
      // // //临时保存
      // ctx.restore();
      // ctx.setFillStyle("#bd2f2f"); // 文字颜色
      // ctx.fillText("3.请保存上方二维码，结款时出示给商家！", 100, 690); // 绘制文字
      // //  //临时保存
      //  ctx.restore();
      // ctx.setFillStyle("#231815"); // 文字颜色
      // ctx.fillText("若是实物奖品，请在餐中联系商家兑付，结款时", 100, 720); // 绘制文字
      // ctx.fillText("出示二维码核销该奖品！", 100, 750); // 绘制文字




      let canvasToTempFilePath = "";
      ctx.draw(false, function () {
        // canvas画布转成图片并返回图片地址
        console.log(111)
        wx.canvasToTempFilePath({
          canvasId: 'myCanvas',
          success: function (res) {
            // console.log(res.tempFilePath)
            canvasToTempFilePath = res.tempFilePath
            that.setData({
              showShareImg: true
            })
            console.log(res.tempFilePath, 'canvasToTempFilePath')
            console.log("绘制成功");
            that.saveShareImg(canvasToTempFilePath);
          },
          fail: function () {
            wx.showToast({
              title: '绘制失败',
            })
          },
          complete: function () {
            wx.hideLoading()
            wx.hideToast()
          }
        })
      })

    })

  },
  drawText: function (ctx, context, leftWidth, initHeight, titleHeight, canvasWidth) {
    //  console.log(str)

    for (var i = 0; i < context.length; i++) {
      var str = context[i];
      var lineWidth = 0;
      var lastSubStrIndex = 0; //每次开始截取的字符串的索引
      ctx.font = 'normal bold 18px Source Han Sans CN';
      ctx.setFillStyle("#231815"); // 文字颜色
      ctx.setTextAlign("left");

      for (let i = 0; i < str.length; i++) {
        lineWidth += ctx.measureText(str[i]).width;
        if (lineWidth > canvasWidth) {

          ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
          initHeight += 30; //16为字体的高度
          lineWidth = 0;
          lastSubStrIndex = i;
          titleHeight += 30;
        }
        if (i == str.length - 1) { //绘制剩余部分
          ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);

        }
      }
      // 标题border-bottom 线距顶部距离
      initHeight = initHeight + 30;
      titleHeight = titleHeight + 10;
    }
    // var res=new Array(ctx,titleHeight);
    return titleHeight;
  },

  // 保存到系统相册
  saveShareImg(canvasToTempFilePath) {
    console.log('canvasToTempFilePath')
    let that = this;
    // 获取用户是否开启用户授权相册
    if (!that.data.openStatus) {
      wx.openSetting({
        success: (result) => {
          console.log("result.authSettingscope.writePhotosAlbum");
          console.log(result.authSetting["scope.writePhotosAlbum"] == true);
          if (result) {
            if (result.authSetting["scope.writePhotosAlbum"] == true) {
              that.setData({
                openStatus: true
              });
              wx.saveImageToPhotosAlbum({
                filePath: canvasToTempFilePath,
                success: function (data) {
                  console.log("success")
                  wx.showToast({
                    title: '图片保存成功',
                    icon: 'none',
                    duration: 1000
                  })
                },
                fail: function (err) {
                  console.log("fail")
                  wx.showToast({
                    title: '保存失败',
                    icon: 'none'
                  })
                }
              })
            }
          }
        },
        fail: () => {
          wx.getSetting({
            success(res) {
              // 如果没有则获取授权
              if (!res.authSetting['scope.writePhotosAlbum']) {
                wx.authorize({
                  scope: 'scope.writePhotosAlbum',
                  success() {
                    that.setData({
                      openStatus: true
                    })
                    wx.saveImageToPhotosAlbum({
                      filePath: canvasToTempFilePath,
                      success() {
                        wx.showToast({
                          title: '图片保存成功',
                          icon: 'none',
                          duration: 1000
                        })
                      },
                      fail() {
                        wx.showToast({
                          title: '保存失败',
                          icon: 'none'
                        })
                      }
                    })
                  },
                  fail() {
                    // 如果用户拒绝过或没有授权，则再次打开授权窗口
                    that.setData({
                      openStatus: false
                    });
                    wx.showModal({
                      title: '用户未授权',
                      content: '您未开启保存图片到相册的权限，设置开启该权限？',
                      success: function (sm) {
                        if (sm.confirm) {
                          wx.openSetting()
                        } else if (sm.cancel) {
                          console.log('用户点击取消')
                        }
                      }
                    })

                  }
                })
              } else {
                // 有则直接保存
                that.setData({
                  openStatus: true
                });
                wx.saveImageToPhotosAlbum({
                  filePath: canvasToTempFilePath,
                  success() {
                    wx.showToast({
                      title: '图片保存成功',
                      icon: 'none',
                      duration: 1000
                    })
                  },
                  fail() {
                    wx.showToast({
                      title: '保存失败',
                      icon: 'none'
                    })
                  }
                })
              }
            },
            fail(err) {
              console.log(err)
            }
          })
        },
        complete: () => {

        }
      });
    } else {
      wx.getSetting({
        success(res) {
          // 如果没有则获取授权
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success() {
                that.setData({
                  openStatus: true
                })
                wx.saveImageToPhotosAlbum({
                  filePath: canvasToTempFilePath,
                  success() {
                    wx.showToast({
                      title: '图片保存成功',
                      icon: 'none',
                      duration: 1000
                    })
                  },
                  fail() {
                    wx.showToast({
                      title: '保存失败',
                      icon: 'none'
                    })
                  }
                })
              },
              fail() {
                // 如果用户拒绝过或没有授权，则再次打开授权窗口
                that.setData({
                  openStatus: false
                });
                wx.showModal({
                  title: '用户未授权',
                  content: '您未开启保存图片到相册的权限，设置开启该权限？',
                  success: function (sm) {
                    if (sm.confirm) {
                      wx.openSetting()
                    } else if (sm.cancel) {
                      console.log('用户点击取消')
                    }
                  }
                })
              }
            })
          } else {
            // 有则直接保存
            console.log("有则直接保存")
            that.setData({
              openStatus: true
            });
            wx.saveImageToPhotosAlbum({
              filePath: canvasToTempFilePath,
              success() {
                wx.showToast({
                  title: '图片保存成功',
                  icon: 'none',
                  duration: 1000
                })
              },
              fail() {
                wx.showToast({
                  title: '保存失败',
                  icon: 'none'
                })
              }
            })
          }
        },
        fail(err) {
          console.log(err)
        }
      })
    }
  },
  closeSuccessNew() {

    const that = this;
    let list = that.data.prizeList;
    let content = "";
    for (var i = 0; i < list.length; i++) {
      let prizeType = list[i].prizeTypeId;
      let status = list[i].status;
      if (prizeType == '1' && (status == '2' || status == '3' || status == '9')) { //红包
        content = '您还有红包未领取';
      }
      if (prizeType == '6' && status != '8') { //红包
        content = '您还有奖品未填写邮寄地址';
      }
      if (prizeType == '' || prizeType == undefined || prizeType == null) { //多选一
        content = '您还有奖品未挑选';
      }
    }

    if (content !== '') {
      wx.showModal({
        title: '提示',
        content: content + ',确认要关闭吗？',
        success: function (sm) {
          if (sm.confirm) {
            that.setData({
              isShowPrizes: false,
              prizeList: null,
              qrcode: '',
              source: ""
            })

            that.queryKingVIPMember();

          } else if (sm.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      that.setData({
        isShowPrizes: false,
        prizeList: null,
        qrcode: '',
      })
      that.queryKingVIPMember();

    }



  },
  operaBut(e) {
    const that = this;
    let item = e.currentTarget.dataset.item; //奖项类型
    let index = e.currentTarget.dataset.index; //index
    if (item.prizeTypeId == '' || item.prizeTypeId == null || item.prizeTypeId == undefined) { //多选一
      wx.navigateTo({
        url: '../receiptInfo/receiptInfo?source=1&prizeInfo=' + JSON.stringify(item) + '&index=' + index,
      })
    }
    if (item.prizeTypeId == '6') { //实物奖
      //跳转到填写礼物页面
      wx.navigateTo({
        url: '../receiptInfo/receiptInfo?source=1&prizeInfo=' + JSON.stringify(item) + '&index=' + index,
      })
    }
    if (item.prizeTypeId == '1') { //红包
      this.prizeDraw(e)
    }
    if (item.prizeTypeId == '3') { //积分
      //存入缓存，点过立即领取
      wx.setStorageSync('goToganguo', true);
      wx.navigateToMiniProgram({
        appId: api.thirdAppId,
        path: 'pages/home/home',
        envVersion: getApp().globalData.ganguoAppidStyle,
        success() {
          //存入缓存，点过立即领取
          wx.setStorageSync('goToganguo', true);
          that.setData({
            'goToganguo': true
          })
        }
      })
    }

  },
  queryJDticketInfo(prizeOrderId, fticketno, status, index) {
    this.isLoading(true, "正在加载...")
    const that = this;
    netWork.POST('QueryTicketInfo', {
      data: {
        prizeOrderId: prizeOrderId,
        fticketno: fticketno
      },
      success: function (res) {
        that.isLoading(false)
        if (res.data.retCode == undefined) {
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          })
        }
        if (res.data.retCode == "0000") { //成功
          if (res.data.data != null && res.data.data != '') {
            that.setData({
              ticket: res.data.data,
              isShowQRcode: true,
              qrcodeBigURL: that.drawImg(res.data.data.FTicketNo)
            })
          }
          if (res.data.data.FSource == '001' && status != 13) { //餐饮
            that.subscribeMessage(prizeOrderId, index, fticketno);
          }


        } else {
          //跳转温馨提示页面
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + res.data.retCode + '&retMsg=' + res.data.retMsg,
          })

        }
      },
      fail: function () {
        that.isLoading(false)
        //跳转温馨提示页面
        wx.redirectTo({
          url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
        })
      }
    })
  },
  // 订阅信息的下发授权
  subscribeMessage: function (prizeOrderId, index, ticketNo) {
    let that = this;
    try {
      //请求立即使用接口
      netWork.POST('ticketUsed', {
        data: {
          userId: wx.getStorageSync('userId'),
          prizeOrderId: prizeOrderId,
          ticketNo: Base64.encode(ticketNo).replace(/=/g,"")
        },
        success: function (res) {
          if (res.data.retCode == "0000") {
            //更新状态为13-核销中
            that.setData({
              ['prizeList[' + index + '].status']: 13
            })
          }

        },
        fail: function (res) {

        }
      });
      wx.getSetting({
        withSubscriptions: true, //这句怎么无效
        success(e) {
          try {
            var mainSwitch = e.subscriptionsSetting.mainSwitch;
            if (mainSwitch) {
              //true，总开关订阅消息
              console.log(e.subscriptionsSetting.itemSettings);
              if (typeof e.subscriptionsSetting.itemSettings != 'undefined') { //
                var size = 0;
                var key;
                var obj = e.subscriptionsSetting.itemSettings;
                for (key in obj) { //obj中存在几个关键字
                  if (obj.hasOwnProperty(key))
                    size++;
                }
                if (size != 2) {
                  that.setData({
                    isSubMsg: true
                  })
                }
              } else { //没有该节点弹出
                that.setData({
                  isSubMsg: true
                })
              }
            }
          } catch (e1) {

          }

        }
      })
      wx.requestSubscribeMessage({
        tmplIds: ['KyJMnBXyKJ1nrCQiMfRDCZnT-JLSMVo1cz98jC85cKg', 'mLYNe8uqrdlB28ymi8g70TMXtaZ-Apc2ZIf_6gbudco'],
        success(res) {
          var subscriptionData = [];
          for (let key in res) {
            if (key !== "errMsg" && key !== "errorCode") {
              let obj = {
                template_id: key,
                status: res[key]
              };
            }
            console.log(res)
            log.info(res);
            that.setData({
              isSubMsg: false
            })
          }


        },
        fail(res) {
          console.log(res);
          that.setData({
            isSubMsg: false
          })
        }
      })
    } catch (err) { // 当前微信版本不支持订阅信息
      console.error("subscribeMessage-err", err);
    }
  },
  //优惠券立即使用
  async ticketDraw(event) {

    //防止重复点击或者点击过快
    console.log("点击了");
    if (!isClick) {
      console.log("重复返回~");
      return;
    }
    if (isClick) {
      isClick = false;
      //定时器
      setTimeout(function () {
        isClick = true;
      }, 2000); //2秒内不能重复点击
    }
    let prizeInfo = event.currentTarget.dataset.item;
    let index = event.currentTarget.dataset.index;
    this.setData({
      ticketName: prizeInfo.prizeName
    })
    const that = this;
    console.log(prizeInfo)

    //状态=2,需要同步
    if (prizeInfo.status == '2' || prizeInfo.fticketNo == '' || prizeInfo.fticketNo == null) {
      netWork.POST('getTicketNo', {
        data: {
          prizeOrderId: prizeInfo.prizeOrderId
        },
        success: function (res) {
          if (res.data.retCode == undefined) {
            wx.redirectTo({
              url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
            })
          }
          if (res.data.retCode == "0000") {
            //成功，调用查询礼券详情接口
            if (res.data.fticketNo == '' || res.data.fticketNo == null) { //礼券为空
              wx.showToast({
                title: '优惠券正在发放',
                icon: 'error',
                duration: 3000
              })
              return;
            } else { //不为空查询金蝶详情接口
              that.queryJDticketInfo(prizeInfo.prizeOrderId, res.data.fticketNo, prizeInfo.status, index);
            }
          } else {
            wx.showToast({
              title: '优惠券正在发放',
              icon: 'error',
              duration: 3000
            })

          }
        },
        fail: function () {
          wx.showToast({
            title: '优惠券正在发放',
            icon: 'error',
            duration: 3000
          })
        }
      })
    } else { //不需要同步，
      let ticket = await that.queryJDticketInfo(prizeInfo.prizeOrderId, prizeInfo.fticketNo, prizeInfo.status, index);

    }

  },
  async closeTicket() {
    this.setData({
      isShowQRcode: false,
      ticket: "",
      qrcodeBigURL: ""
    })


  },
  /**
   * 红包兑奖
   * @param {*} event 
   */
  prizeDraw: function (e) {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    let prizeInfo = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    if (prizeInfo.status == '8') {
      return;
    }
    api.showLoading('正在领取...');
    const that = this;
    log.info('[prizeRecord]--->[receiveWxRedBag]')

    //兑奖
    netWork.POST('receiveWxRedBag', {
      data: {
        userId: wx.getStorageSync('userId'),
        prizeOrderId: prizeInfo.prizeOrderId,
        prizeId: prizeInfo.prizeId,
        positioningStyle: wx.getStorageSync('positioningStyle') == '' ? '0' : wx.getStorageSync('positioningStyle'),
        positioningType: wx.getStorageSync('positioningType') == '' ? '-1' : wx.getStorageSync('positioningType'),
        latitude: wx.getStorageSync('latitude'),
        longitude: wx.getStorageSync('longitude'),
        speed: wx.getStorageSync('speed'),
        accuracy: wx.getStorageSync('accuracy'),
        source: 1, //兑奖来源，1-正常流程兑奖 2-中奖记录兑奖
      },
      success: function (res) {
        api.cancelLoading();
        if (res.data.retCode == undefined) {
          setTimeout(function () {
            wx.showToast({
              title: '领取失败',
              icon: 'error',
              duration: 3000
            })
          }, 200);

        }
        if (res.data.retCode == "0000") {
          setTimeout(function () {
            wx.showToast({
              title: '领取成功',
              icon: 'success',
              duration: 3000
            })
          }, 200);

          //更新该prizeOrderid对应的状态
          that.setData({
            ['prizeList[' + index + '].status']: 8
          })
          //更新缓存中的prizeList
          wx.setStorageSync('prizeList', that.data.prizeList);

        } else {
          setTimeout(function () {
            wx.showToast({
              title: '领取失败',
              icon: 'error',
              duration: 3000
            })
          }, 200);

        }

      },
      fail: function () {
        wx.showToast({
          title: '领取失败',
          icon: 'error',
          duration: 3000
        })
      }
    });


  },

  //问卷第1页关闭
  close1Page() {
    this.setData({
      isQuestMask: false,
      questPage: 1
    })
    const that = this;
    wx.setStorageSync('isQuest', false) //不做问卷
    setTimeout(function () {
      if (!that.data.isShowPrizes) {
        let query = wx.createSelectorQuery();
        query.select('.bnt-rm').boundingClientRect(rect => {
          let clientWidth = rect.width;
          let ratio = 750 / clientWidth;
          let clientTop = rect.top;
          let top = clientTop * ratio - 350;
          that.setData({
            pubtop: top,
            isShowPub: true
          })
        }).exec();
      }
    }, 1000)


  },
  //goto问卷第2页
  goto2Page() {

    //去下一页
    this.setData({
      questPage: 2
    })


  },
  //goto问卷第3页
  goto3Page() {
    //非空校验
    if (this.data.index == null || this.data.index == undefined ||
      this.data.index2 == null || this.data.index2 == undefined ||
      this.data.index3 == null || this.data.index3 == undefined) {
      setTimeout(function () {
        wx.showToast({
          title: '您还有题目未答完哦~',
          icon: 'none'
        })
      }, 100)
      return;
    }
    this.setData({
      questPage: 3
    })
    var temp = this.data.questionAnswer;
    temp[1] = this.data.index;
    temp[2] = this.data.index2;
    temp[3] = this.data.index3;
    //拼接答案
    this.setData({
      questionAnswe: temp
    })
  },
  //goto问卷第4页
  goto4Page() {
    //非空校验
    if (this.data.index4 == null || this.data.index4 == undefined ||
      this.data.index5 == null || this.data.index5 == undefined ||
      this.data.index6 == null || this.data.index6 == undefined) {
      setTimeout(function () {
        wx.showToast({
          title: '您还有题目未答完哦~',
          icon: 'none'
        })
      }, 100)
      return;
    }
    this.setData({
      questPage: 4
    })
    var temp = this.data.questionAnswer;
    temp[4] = this.data.index4;
    temp[5] = this.data.index5;
    temp[6] = this.data.index6;
    //拼接答案
    this.setData({
      questionAnswe: temp
    })
  },

  //goto问卷第5页
  goto5Page() {
    //非空校验
    if (this.data.star1 == 0 || this.data.star2 == 0 || this.data.star3 == 0 || this.data.star4 == 0) {
      setTimeout(function () {
        wx.showToast({
          title: '您还有题目未答完哦~',
          icon: 'none'
        })
      }, 100)
      return;
    }
    this.setData({
      questPage: 5
    })
    //提交的答案
    var temp = this.data.questionAnswer;
    temp[7] = this.data.star1 + "," + this.data.star2 + "," + this.data.star3 + "," + this.data.star4;

    //拼接答案
    this.setData({
      questionAnswe: temp
    })
    //请求金蝶增加积分
    this.saveAnswer();



  },
  /**
   *增加积分
   */
  saveAnswer: function () {
    const that = this;
    var ans = JSON.stringify(that.data.questionAnswer);
    ans = ans.replace('{', '').replace('}', '').replace(/"/g, 'a')
    // ans =   
    netWork.POST('xhtx/little/saveAnswer', {
      data: {
        userId: wx.getStorageSync('userId'),
        cardNo: that.data.cardNo, //卡号
        questionAnswer: ans, //答案
        prizeOrderId: that.data.prizeOrderId
      },
      success: function (res) {

      },
      fail: function () {

      }
    });

  },

  //第1题的点击事件
  goIndex1(event) {
    let index = event.currentTarget.dataset.index;
    this.setData({
      index: index
    })
  },
  //第2题的点击事件
  goIndex2(event) {
    let index = event.currentTarget.dataset.index;
    this.setData({
      index2: index
    })
  },
  //第3题的点击事件
  goIndex3(event) {
    let index = event.currentTarget.dataset.index;
    this.setData({
      index3: index
    })
  },
  //第4题的点击事件
  goIndex4(event) {
    let index = event.currentTarget.dataset.index;
    this.setData({
      index4: index
    })
  },
  //第5题的点击事件
  goIndex5(event) {
    let index = event.currentTarget.dataset.index;
    this.setData({
      index5: index
    })
  },
  //第6题的点击事件
  goIndex6(event) {
    let index = event.currentTarget.dataset.index;
    this.setData({
      index6: index
    })
  },
  //第7题的点击事件
  goIndex7(event) {
    let index = event.currentTarget.dataset.index;
    this.setData({
      index7: index
    })
  },
  //问卷完成
  finishQuest() {
    this.setData({
      isFinsh: true
    });
    const that = this;

    setTimeout(function () {
      that.setData({
        isQuestMask: false
      });
    }, 1000)
    setTimeout(function () {
      if (!that.data.isShowPrizes) {
        let query = wx.createSelectorQuery();
        query.select('.bnt-rm').boundingClientRect(rect => {
          let clientWidth = rect.width;
          let ratio = 750 / clientWidth;
          let clientTop = rect.top;
          let top = clientTop * ratio - 350;
          that.setData({
            pubtop: top,
            isShowPub: true
          })
        }).exec();
      }
    }, 2500)





  },
  adviceMsgInput(e) {
    var temp = this.data.questionAnswer;
    var value = e.detail.value.length; //输入内容的长度
    var lastArea = 100 - value; //剩余字数
    temp[8] = e.detail.value;
    this.setData({
      questionAnswer: temp,
      lastArea: lastArea
    })
  },
  changeStar(event) {
    let star1 = event.currentTarget.dataset.star1; //第一组星星
    let star2 = event.currentTarget.dataset.star2; //第二组星星
    let star3 = event.currentTarget.dataset.star3; //第三组星星
    let star4 = event.currentTarget.dataset.star4; //第四组星星

    if (star1 != undefined) {
      this.setData({
        star1: star1,
        move1: this.data.move1 ? false : true
      })
    }
    if (star2 != undefined) {
      this.setData({
        star2: star2,
        move2: this.data.move2 ? false : true
      })
    }
    if (star3 != undefined) {
      this.setData({
        star3: star3,
        move3: this.data.move3 ? false : true
      })
    }
    if (star4 != undefined) {
      this.setData({
        star4: star4,
        move4: this.data.move4 ? false : true
      })
    }

  },
  isLoading(isLoading, loadingText) {
    this.setData({
      isLoading: isLoading,
      loadingText: loadingText
    })

  },
  showQuest() {
    this.queryKingVIPMember();
  },
  closeMaskPub() {
    this.setData({
      isShowPub: false
    })
    const that = this;
    let query = wx.createSelectorQuery();
    query.select('.bnt-rm').boundingClientRect(rect => {
      let clientWidth = rect.width;
      let ratio = 750 / clientWidth;
      let clientTop = rect.top;
      let top = clientTop * ratio - 350;
      setTimeout(function () {
        that.setData({
          pubtop: top,
          isShowMore: true
        })
      }, 500);
      that.setData({
        top: top,
      })
    }).exec();

  },
  closeMask() {
    this.setData({
      isShowMore: false
    })


  },
  //查询总共打开多少瓶
  getOpendCount(qrCode) {
    const that = this;
    //兑奖
    netWork.POST('getOpendCount', {
      data: {
        userId: wx.getStorageSync('userId'),
        qrcodeAPublish: qrCode
      },
      success: function (res) {
        if (res.data.retCode == "0000") {
          console.log(res.data);
          var opendCount = res.data.data.opendCount;
          if (typeof opendCount != 'undefined') {
            that.setData({
              opendCount: opendCount,
              nextPrizeShow: opendCount >= 2 ? 'car' : 'gold',
              showNext: true
            })
          }
        }

      },
      fail: function (res) {

      }
    });
  },
  closeSub() {
    this.setData({
      isSubMsg: false
    })
  },
  error(event){
    console.log(event.detail)
  },
  load(event){
    console.log(event.detail)
  },
  //允许授权名称和头像
  async authNameAndPhoto(e){
    if(e.detail){
       this.updateJSCode();
       //已成功授权用户信息，并保存
       wx.setStorageSync('getUserinfo', true);
       console.log("开始授权手机号")
       this.setData({ //显示拒绝授权提示层
           isShowModalAuth: true,
           authText: "为了保证正常获取奖励，现需获取您的手机号码",
           isPhone: '1'
       })
    }
 },
 //显示授权用户头像和昵称弹板
 showModel(e){
   this.setData({
       isShowModalAuth: false
   })
   this.selectComponent('#showmodel').showModel();
 },
 //隐藏授权用户头像和昵称弹板
 hideAuthModal(){
   this.setData({
       isShowModalAuth: true,
       authText: "为了保证正常获取奖励，现需获取您的头像昵称"
   })
 }
})